package org.example.practice.about_properties;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * 读取properties文件
 *
 * @Author: WangShengJie
 * @Date: 2025/4/18
 */
@Component
@Slf4j
public class ReadProperties {

    /**
     * 读取properties文件
     * @param key key
     * @return key为空或不存在，返回值为null
     */
    public String readProperties(String key) {
        FileInputStream fileInputStream = null;
        Properties properties = new Properties();
        String value = "";
        try {
            fileInputStream = new FileInputStream("src/main/resources/demo.properties");
            properties.load(fileInputStream);
            value = properties.getProperty(key);
            log.info("读取properties文件-->{}={}", key, value);
        } catch (FileNotFoundException e) {
            log.error("读取properties文件-->失败！读取key:{}", key, e);
        } catch (IOException ioException) {
            log.error("读取properties文件-->失败！读取key:{}", key, ioException);
        }finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }
}
